package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码（避免中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 日志记录
        System.out.println("Login请求: " + request.getRemoteAddr() + " - " + request.getParameter("username"));

        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 1. 校验参数（非空判断）
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            System.out.println("登录失败: 用户名或密码为空");
            // 失败时，转发回登录页并提示错误
            request.setAttribute("errorMsg", "用户名和密码不能为空！");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String userRole = null;

        try {
            // 2. 加载数据库驱动 & 建立连接
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC";
            String dbUser = "webdb";
            String dbPassword = "webdb";
            conn = DriverManager.getConnection(url, dbUser, dbPassword);

            // 3. 查询用户（含角色）- 修改此处：使用 username 字段而非 mName
            String sql = "SELECT * FROM `shixun` WHERE username = ? AND mpwd = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 登录成功：获取角色 + 写入 Session
                userRole = rs.getString("role");
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                session.setAttribute("role", userRole);

                System.out.println("登录成功: " + username + "，角色：" + userRole);

                // 4. 根据角色跳转不同页面
                if ("管理人员".equals(userRole)) {
                    response.sendRedirect("main.jsp");
                } else if ("检查人员".equals(userRole)) {
                    response.sendRedirect("main.jsp");
                } else {
                    response.sendRedirect("index.jsp");
                }

            } else {
                // 登录失败：用户名或密码错误
                System.out.println("登录失败: " + username + " - 用户名或密码错误");
                request.setAttribute("errorMsg", "用户名或密码错误！");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }

        } catch (ClassNotFoundException e) {
            // 系统错误：驱动加载失败
            System.err.println("数据库驱动加载失败: " + e.getMessage());
            request.setAttribute("errorMsg", "系统错误，请联系管理员");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (SQLException e) {
            // 数据库错误：连接或查询异常
            System.err.println("数据库操作失败: " + e.getMessage());
            request.setAttribute("errorMsg", "数据库错误，请稍后重试");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } finally {
            // 5. 关闭数据库资源
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}